package com.wosai.register.util;

import java.sql.Timestamp;
import java.util.Calendar;

public class DateUtil {
    
    public static Timestamp firstDayOfMonth(Timestamp now)
    {
        Calendar cal = getCalendarOfTheDay(now);
        cal.set(Calendar.DATE, 1);
        return new Timestamp(cal.getTimeInMillis());
    }

    public static Timestamp firstDayOfQuarter(Timestamp now)
    {
        Calendar cal = getCalendarOfTheDay(now);
        int month = cal.get(Calendar.MONTH);
        
        int firstMonthOfQuarter = (month / 3) * 3;
        
        cal.set(Calendar.MONTH, firstMonthOfQuarter);
        cal.set(Calendar.DATE, 1);
        return new Timestamp(cal.getTimeInMillis());
    }
    
    public static Timestamp firstDayOfWeek(Timestamp now)
    {
        Calendar cal = getCalendarOfTheDay(now);
        cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
        return new Timestamp(cal.getTimeInMillis());
    }

    public static Timestamp today(Timestamp now)
    {
        Calendar cal = getCalendarOfTheDay(now);
        return new Timestamp(cal.getTimeInMillis());
    }

    public static Timestamp max(Timestamp t1, Timestamp t2){
        return t1.compareTo(t2)>0? t1: t2;
    }
    
    private static Calendar getCalendarOfTheDay(Timestamp now) {
        Calendar cal = Calendar.getInstance();
        cal.setTime(now);
        cal.set(Calendar.HOUR_OF_DAY, 0);
        cal.clear(Calendar.MINUTE);
        cal.clear(Calendar.SECOND);
        cal.clear(Calendar.MILLISECOND);

        cal.setFirstDayOfWeek(Calendar.MONDAY);
        return cal;
    }
    
    public static Timestamp ndaysFromNow(Timestamp now, int ndays) {
        Calendar cal = getCalendarOfTheDay(now);
        cal.add(Calendar.DAY_OF_MONTH, ndays);
        return new Timestamp(cal.getTimeInMillis());
    }
    
    public static Timestamp nmonthsFromNow(Timestamp now, int nmonths) {
        Calendar cal = getCalendarOfTheDay(now);
        cal.add(Calendar.MONTH, nmonths);
        return new Timestamp(cal.getTimeInMillis());
    }

    public static Timestamp now(){
        return new Timestamp(System.currentTimeMillis());
    }

    public static void main(String[] args){
        Timestamp now = Timestamp.valueOf("2013-08-27 11:01:01");
        
        System.err.println("First day of month: " + firstDayOfMonth(now));
        System.err.println("First day of quarter: " + firstDayOfQuarter(now));
        System.err.println("First day of week: " + firstDayOfWeek(now));
        
        System.err.println("Epoch: " + new Timestamp(0));
        
    }
}
